package example.dao;

import example.entity.Comment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 评论数据访问对象
 *
 * @author 张心怡
 * @date 2024/12/16
 */
public class CommentDao extends BaseDAO {

    private static final String INSERT_COMMENT_SQL = "INSERT INTO message (user_id, book_id, date, message) VALUES (?,?,?,?)";
    private static final String SELECT_COMMENTS_BY_BOOK_ID_SQL = "SELECT * FROM message WHERE book_id =?";

    public static void deleteComment(int id) {
        String sql = "DELETE FROM message WHERE id =?";
        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setInt(1, id);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void addComment(Comment comment) {
        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(INSERT_COMMENT_SQL)) {
            preparedStatement.setInt(1, comment.getUserId());
            preparedStatement.setInt(2, comment.getBookId());
            preparedStatement.setDate(3, new java.sql.Date(comment.getDate().getTime()));
            preparedStatement.setString(4, comment.getMessage());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static List<Comment> getCommentsByBookId(int bookId) {
        List<Comment> comments = new ArrayList<>();
        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(SELECT_COMMENTS_BY_BOOK_ID_SQL)) {
            preparedStatement.setInt(1, bookId);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    Comment comment = new Comment();
                    comment.setId(resultSet.getInt("id"));
                    comment.setUserId(resultSet.getInt("user_id"));
                    comment.setBookId(resultSet.getInt("book_id"));
                    comment.setDate(resultSet.getDate("date"));
                    comment.setMessage(resultSet.getString("message"));
                    comments.add(comment);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return comments;
    }
}
